// 引入宠物服务
const petService = require('../../services/pet');

Page({
  data: {
    pets: [],
    currentPage: 1,
    pageSize: 10,
    total: 0,
    hasMoreData: true,
    isLoading: false
  },

  onLoad: function() {
    this.loadPets();
  },
  
  onShow: function() {
    // 刷新列表，因为可能从其他页面添加或编辑宠物后返回
    this.setData({
      currentPage: 1,
      pets: [],
      hasMoreData: true
    });
    this.loadPets();
  },
  
  // 加载宠物列表
  loadPets: function() {
    if (this.data.isLoading) return;
    
    this.setData({ isLoading: true });
    wx.showNavigationBarLoading();
    
    petService.getPetList(this.data.currentPage, this.data.pageSize)
      .then(res => {
        const pets = this.data.currentPage === 1 ? res.records : [...this.data.pets, ...res.records];
        
        this.setData({
          pets,
          total: res.total,
          hasMoreData: pets.length < res.total,
          isLoading: false
        });
        
        wx.hideNavigationBarLoading();
      })
      .catch(err => {
        console.error('获取宠物列表失败', err);
        this.setData({ isLoading: false });
        wx.hideNavigationBarLoading();
        
        wx.showToast({
          title: '获取宠物列表失败',
          icon: 'none'
        });
      });
  },
  
  // 加载更多宠物
  loadMorePets: function() {
    if (!this.data.hasMoreData || this.data.isLoading) return;
    
    this.setData({
      currentPage: this.data.currentPage + 1
    });
    
    this.loadPets();
  },
  
  // 跳转到添加宠物页面
  navigateToAddPet: function() {
    wx.navigateTo({
      url: '/pages/pet/add'
    });
  },
  
  // 跳转到宠物详情页面
  navigateToPetDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/pet/detail?id=${id}`
    });
  },
  
  // 跳转到编辑宠物页面
  navigateToEditPet: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/pet/edit?id=${id}`
    });
  },
  
  // 跳转到宠物健康档案页面
  navigateToRecords: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/medical/index?petId=${id}`
    });
  },
  
  // 下拉刷新
  onPullDownRefresh: function() {
    this.setData({
      currentPage: 1,
      pets: [],
      hasMoreData: true
    });
    
    this.loadPets();
    
    wx.stopPullDownRefresh();
  },
  
  // 上拉加载更多
  onReachBottom: function() {
    this.loadMorePets();
  },
  
  onShareAppMessage: function() {
    return {
      title: '我的宠物 - 宠物医院',
      path: '/pages/index/index'
    };
  }
}); 